package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.TaoHua;
import com.itheima.service.mongo.TaoHuaService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

@DubboService
public class TaoHuaServiceImpl implements TaoHuaService {

    @Autowired
    MongoTemplate mongoTemplate;

    //保存
    @Override
    public String save(TaoHua taoHua) {

        mongoTemplate.save(taoHua);
        return taoHua.getId().toHexString();
    }

    //随机查询 一条语音
    @Override
    public TaoHua randomFind(Long userId) {
        //status需要为0
        Query query = new Query(Criteria.where("status").is(0).and("userId").ne(userId)).limit(1);
        TaoHua taoHua = mongoTemplate.findOne(query, TaoHua.class);
        if (taoHua == null){
            return null;
        }
        //修改桃花状态
        taoHua.setStatus(1);
        Update update = new Update();
        update.set("status",1);
        Query query1 =Query.query(Criteria.where("id").is(taoHua.getId()));
        mongoTemplate.updateFirst(query1,update,TaoHua.class);
        return taoHua;

    }
}
